package com.controller;

import com.constant.Constant;
import com.entity.User;
import com.service.RegisterService;
import com.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class RegisterController {

    @Autowired
    RegisterService registerService;

    //注册
    @PostMapping("/regist.do")
    public AjaxResult add(User user, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        User user1 = registerService.addRegister(user);
        boolean flag =true;
        if(user1.getRole().equals("admin")){
            boolean b = flag = false;
            ajaxResult.setMsg("该角色无法注册");
        }else{
            ajaxResult.setMsg("先注册，在修改后台");
        }
        request.getSession().setAttribute(Constant.SESSION_USER, user1);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    //注册检验邮箱和密码格式
    @PostMapping("/check.do")
    public AjaxResult checkName(String login_name) {
        AjaxResult ajaxResult1 = new AjaxResult();
        String s1 = registerService.checkNameService(login_name);
        if( login_name.matches("^[0-9a-zA-Z_]{1,}$")){
            ajaxResult1.setSuccess(true);
        }else{
            ajaxResult1.setSuccess(false);
            ajaxResult1.setMsg("格式错误");
            return ajaxResult1;
        }
        if (s1 != null) {
               ajaxResult1.setSuccess(false);
               ajaxResult1.setMsg("登录名重复");
               ajaxResult1.setMsg("登录名重复");
                return ajaxResult1;
           }else{
                ajaxResult1.setSuccess(true);
           }
        return ajaxResult1;
    }

    @RequestMapping("/checkEmail")
    public AjaxResult checkEmail(String email) {
        boolean b = registerService.checkEmailService(email);
        AjaxResult ajaxResult2 = new AjaxResult();
        if(email.matches("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$")){
           ajaxResult2.setSuccess(true);
        }else{
            ajaxResult2.setSuccess(false);
            ajaxResult2.setMsg("格式错误");
            return ajaxResult2;
        }
        if (b) {
            ajaxResult2.setSuccess(false);
            ajaxResult2.setMsg("请重新输入");
            return ajaxResult2;
        }else{
            ajaxResult2.setSuccess(true);
        }
        return ajaxResult2;
    }
}